<template>
    <div class="dropdown" ref="dropdownRef">
        <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">
          {{title}}
        </a>
        <ul class="dropdown-menu" :style="{dispaly: 'block !important'}" v-if="isOpen">
          <slot></slot>
        </ul>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import useClickOutside from '../hooks/useClickOutside'
export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      requried: true
    }
  },
  setup () {
    const isOpen = ref(false)
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }
    const dropdownRef = ref<null | HTMLElement>(null)
    const { isClickOutside } = useClickOutside(dropdownRef)

    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })
    return {
      isOpen,
      toggleOpen,
      // 返回和ref同名的响应式对象,就可以拿到对应的dom节点
      dropdownRef
    }
  }
})
</script>
<style lang="scss">
.dropdown-menu {
    display: block !important;
}
</style>
